{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Winter sea ice growth\n",
    "\n",
    "This notebook plots change in ice thickness and change in ice type to get a clearer picture of the dynamics of sea ice growth and differences between winter 2018-19 and 2019-20. It utilizes ICESat-2 sea ice thickness, along with [OSI-SAF sea ice type](http://www.osi-saf.org/?q=content/global-sea-ice-type-c) (included in the ICESat-2 monthly gridded sea ice data), to make the plots generated in the notebook.\n",
    " \n",
    " \n",
    "**Input**:\n",
    " - xarray dataset from the jupyter book's google bucket\n",
    " \n",
    " \n",
    " **Output**: \n",
    "  - Plots of sea ice thickness and sea ice type in the Arctic"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{tip}\n",
    "Try running this notebook in Google Colab! Toggle over the rocketship icon at the top of the page and click Colab to open a new window and run the notebook. <br><br>To run a single cell, type **Shift+Enter**. To run the whole notebook, under **Runtime** click **Run all**. Note that you will have to run the notebook from the very beginning and load all the Google Colab dependencies for the code to work.\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "#this cell will load dependencies for running the notebook in Google Colab\n",
    "#this cell may take a while to run\n",
    "import sys\n",
    "\n",
    "#if code is running in google colab, run these cells to install neccessary libraries\n",
    "if 'google.colab' in sys.modules: \n",
    "    !pip install netcdf4\n",
    "    !pip install xarray==0.16.0 "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Import notebook dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import xarray as xr\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "#increase resolution for notebook outputs\n",
    "%config InlineBackend.figure_format = 'retina'\n",
    "import matplotlib as mpl\n",
    "mpl.rcParams['figure.dpi'] = 125"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load data into notebook\n",
    "Copy file from the book's google bucket and load into an xarray dataset. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "!gsutil -m cp gs://is2-pso-seaice/icesat2-book-data.nc ./\n",
    "dataset = xr.open_dataset('icesat2-book-data.nc')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Restrict dataset to region of interest"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "#function from regional_analysis notebook\n",
    "def restrictRegionally(dataset, regionKeyList): \n",
    "    \"\"\"Restrict dataset to input regions.\n",
    "    \n",
    "    Args: \n",
    "        dataset (xr Dataset): dataset generated by Load_IS2 notebook\n",
    "        regionKeyList (list): list of region keys to restrict data to \n",
    "        \n",
    "    Returns: \n",
    "        regionalDataset (xr Dataset): dataset with restricted data to input regions\n",
    "    \"\"\"\n",
    "    \n",
    "    def checkKeys(regionKeyList, regionTbl): \n",
    "        \"\"\"Check that regionKeyList was defined correctly\n",
    "\n",
    "        Raises: \n",
    "            ValueError if regionKeyList was not defined correctly \n",
    "            warning if all data was removed from the dataset\n",
    "        \"\"\"\n",
    "        if type(regionKeyList) != list: #raise a ValueError if regionKeyList is not a list \n",
    "            raise ValueError('regionKeyList needs to be a list. \\nFor example, if you want to restrict data to the Beaufort Sea, define regionKeyList = [13]')\n",
    "\n",
    "        for key in regionKeyList: \n",
    "            if key not in list(regionTbl['key']): \n",
    "                raise ValueError('Region key ' + str(key) + ' does not exist in region mask. \\n Redefine regionKeyList with key numbers from table')\n",
    "\n",
    "        if len(regionKeyList) == 0: \n",
    "            warnings.warn('You removed all the data from the dataset. Are you sure you wanted to do this? \\n If not, make sure the list regionKeyList is not empty and try again. \\n If you intended to keep data from all regions, set regionKeyList = list(tbl[\\\"key\\\"])')\n",
    " \n",
    "    #create a table of keys and labels\n",
    "    regionMask = dataset.region_mask.attrs\n",
    "    regionTbl = pd.DataFrame({'key': regionMask['keys'], 'label': regionMask['labels']})\n",
    "    \n",
    "    #call function to check if regionKeyList was defined correctly\n",
    "    checkKeys(regionKeyList, regionTbl)\n",
    "    \n",
    "    #keys to remove (all keys that are note listed in regionKeyList)\n",
    "    keysToRemove = [key for key in list(regionTbl['key']) if key not in regionKeyList]\n",
    "    \n",
    "    #filter elements from the ice thickness DataArray where the region is the desired region\n",
    "    regionalDataset = dataset.copy()\n",
    "    for var in dataset.data_vars: \n",
    "        if var != 'seaice_conc_monthly_cdr':\n",
    "            regionalVar = regionalDataset[var]\n",
    "            for key in keysToRemove: \n",
    "                regionalVar = regionalVar.where(regionalVar['region_mask'] != key)\n",
    "            regionalDataset[var] = regionalVar\n",
    "    \n",
    "    #find name of labels \n",
    "    labels = [regionTbl[regionTbl['key'] == key]['label'].item() for key in regionKeyList]\n",
    "    \n",
    "    #add new attributes describing changes made to the dataset\n",
    "    if len(labels) < len(regionTbl['key']): \n",
    "        if set(regionKeyList) == set([10,11,12,13,15]): #convert to sets so unordered lists are compared\n",
    "            regionalDataset.attrs['regions with data'] = 'Inner Arctic'\n",
    "        else:    \n",
    "            regionalDataset.attrs['regions with data'] = ('%s' % ', '.join(map(str, labels)))\n",
    "        print('Regions selected: ' + regionalDataset.attrs['regions with data'])\n",
    "    else: \n",
    "        regionalDataset.attrs['regions with data'] = 'All'\n",
    "        print('Regions selected: All \\nNo regions will be removed')\n",
    "    \n",
    "    return regionalDataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#define a list of keys corresponding to the region of interest\n",
    "regionKeyList = [10,11,12,13,15] #Inner Arctic\n",
    "\n",
    "#restrict data to that region\n",
    "dataset = restrictRegionally(dataset, regionKeyList)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Calculate and plot mean monthly data\n",
    "Add mean monthly data as coordinates to the dataset and plot the data for two winters."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Calculate mean monthly values and add to dataset\n",
    "Define a function to calculate mean monthly uncertainity and mean monthly ice thicknesses for all ice types combined, multi year ice, and first year ice, and add data as coordinates to the dataset. Then, call the function to update the dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def calcMeans(dataset): \n",
    "    \"\"\"Calculates mean monthly uncertainity and mean monthly ice thicknesses for all ice types combined, multi year ice, and first year ice, and adds data as coordinates to the dataset.\n",
    "    \n",
    "    Args: \n",
    "        dataset (xr Dataset): dataset generated by Load_IS2 notebook\n",
    "    \n",
    "    Returns: \n",
    "        datasetMeans (xr Dataset): dataset with means added as data variables to the input dataset\n",
    "    \"\"\"  \n",
    "    #calculate mean uncertainites \n",
    "    meanUnc = dataset['ice_thickness_unc_filled'].mean(dim = ['x','y'], skipna = True)\n",
    "    meanUnc.attrs = {'description': 'mean monthly ice thickness uncertainty', 'units': 'meters'}\n",
    "    \n",
    "    #calculate mean thickness for all ice types\n",
    "    meanThickness = dataset['ice_thickness_filled'].mean(dim = ['x','y'], skipna = True)\n",
    "    meanThickness.attrs = {'description': 'mean monthly ice thickness for all ice types', 'units': 'meters'}\n",
    "    \n",
    "    #calculate mean thickness for multi year ice\n",
    "    MYIThickness = dataset['ice_thickness_filled'].where(dataset['ice_type_filled'] == 1)\n",
    "    meanMYIThickness = MYIThickness.mean(dim = ['x','y'], skipna = True)\n",
    "    meanMYIThickness.attrs = {'description': 'mean monthly multi year ice thickness', 'units': 'meters'}\n",
    "    \n",
    "    #calculate mean thickness for first year ice \n",
    "    FYIThickness = dataset['ice_thickness_filled'].where(dataset['ice_type_filled'] == 0)\n",
    "    meanFYIThickness = FYIThickness.mean(dim = ['x','y'], skipna = True)\n",
    "    meanFYIThickness.attrs = {'description': 'mean monthly first year ice thickness', 'units': 'meters'}\n",
    "    \n",
    "    #add means as coordinates to dataset\n",
    "    datasetMeans = dataset.assign_coords(coords = {'mean_ice_thickness_unc': meanUnc, 'mean_ice_thickness': meanThickness, \n",
    "                'mean_MYI_thickness': meanMYIThickness, 'mean_FYI_thickness': meanFYIThickness})\n",
    "    \n",
    "    return datasetMeans"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Call function to update dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset = calcMeans(dataset)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Plot mean monthly ice thickness for two winter seasons \n",
    "Produce a figure that shows mean monthly ice thickness and associated mean monthly uncertainities for two winter seasons.\n",
    " - Choose a start year, defined <span style=\"color:darkmagenta; font-family: Courier\">yearStart</span>, and the function will plot data from that winter and the next \n",
    "     - i.e. setting <span style=\"color:darkmagenta; font-family: Courier\">yearStart = 2018</span> would plot data for winter 18-19 and winter 19-20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plotThicknessCompare(dataset, yearStart = 2018, regionsText = None, figPath = None):\n",
    "    \"\"\" Plots mean monthly ice thickness for two winter seasons. \n",
    "    \n",
    "    Args: \n",
    "        dataset (xr Dataset): dataset generated by Load_IS2 notebook\n",
    "        yearStart (int): year to start plot at (default to 2018)\n",
    "        regionsText(str, optional): string describing regions containing data, if user wants to define the region themself (default to None)\n",
    "        figPath (str, optional): path to save fig (default to None)\n",
    "        \n",
    "    Returns: \n",
    "        Figure displayed in notebook \n",
    "     \n",
    "    Restrictions: \n",
    "        dataset input needs to contain the following coordinates: mean_ice_thickness_unc, mean_ice_thickness, mean_MYI_thickness, mean_FYI_thickness \n",
    "    \"\"\"\n",
    "        \n",
    "    #initialize figure\n",
    "    fig = plt.figure()\n",
    "    ax = plt.axes([0, 0, 1, 1]) \n",
    "    title = plt.title('Mean Monthly Ice Thickness & Uncertainty', y = 1.11, x = 0.5, fontsize = 'x-large', horizontalalignment = 'center')\n",
    "    gridlines = plt.grid(b = True, linestyle = '--', alpha = 0.4) #add gridlines \n",
    "    \n",
    "    #add title describing regions with data \n",
    "    if 'regions with data' in list(dataset.attrs.keys()): \n",
    "        regionsText = dataset.attrs['regions with data']\n",
    "        regionsTitle = ax.text(x = 0.5, y = 1.05, s = 'Region/s: ' + regionsText, size = 12, transform=ax.transAxes, fontsize = 'large', horizontalalignment = 'center')\n",
    "\n",
    "    #get list of months for plotting x axis \n",
    "    winterMonths = ['Nov','Dec','Jan','Feb','Mar','Apr']\n",
    "\n",
    "    #plot data for winter 1\n",
    "    datasetWinter1 = dataset.sel(time = slice('Nov ' + str(yearStart), 'Apr' + str(yearStart + 1)))\n",
    "    winter1Str = 'Winter ' + str(yearStart)[2:4] + '-' + str(yearStart + 1)[2:4]\n",
    "    color1 = 'royalblue'\n",
    "    ax.plot(winterMonths, datasetWinter1['mean_ice_thickness'].values, color = color1, linestyle = '-', marker = 'o', label = winter1Str + ' ice thickness')\n",
    "    ax.fill_between(winterMonths, datasetWinter1['mean_ice_thickness'].values - datasetWinter1['mean_ice_thickness_unc'].values, datasetWinter1['mean_ice_thickness'].values + datasetWinter1['mean_ice_thickness_unc'].values, facecolor = color1, alpha = 0.1, edgecolor = 'none', label = winter1Str + ' uncertainty')\n",
    "    #ax.errorbar(winterMonths, datasetWinter1['mean_ice_thickness'].values, yerr = datasetWinter1['mean_ice_thickness_unc'].values, color = color1, alpha = 0.7, capsize = 3, zorder = 2, label = winter1Str)        \n",
    "    \n",
    "    #plot data for winter 2\n",
    "    datasetWinter2 = dataset.sel(time = slice('Nov ' + str(yearStart + 1), 'Apr' + str(yearStart + 2)))\n",
    "    winter2Str = 'Winter ' + str(yearStart + 1)[2:4] + '-' + str(yearStart + 2)[2:4]\n",
    "    color2 = 'darkgoldenrod'\n",
    "    ax.plot(winterMonths, datasetWinter2['mean_ice_thickness'].values, color = color2, linestyle = '-', marker = 's', label = winter2Str + ' ice thickness')\n",
    "    ax.fill_between(winterMonths, datasetWinter2['mean_ice_thickness'].values - datasetWinter2['mean_ice_thickness_unc'].values, datasetWinter2['mean_ice_thickness'].values + datasetWinter2['mean_ice_thickness_unc'].values, facecolor = color2, alpha = 0.1, edgecolor = 'none', label = winter2Str + ' uncertainty')\n",
    "    #ax.errorbar(winterMonths, datasetWinter2['mean_ice_thickness'].values, yerr = datasetWinter2['mean_ice_thickness_unc'].values, color = color2, alpha = 0.7, capsize = 3, zorder = 2, label = winter2Str)        \n",
    "    \n",
    "    #add legend & labels\n",
    "    ax.legend(loc = 'best', fontsize = 10)\n",
    "    ax.set_ylabel('Mean monthly ice thickness & uncertainty (m)')\n",
    "    ax.set_xlabel('Month')\n",
    " \n",
    "    #save figure\n",
    "    if figPath != None:\n",
    "        plt.savefig(figPath, dpi = 200)\n",
    "        \n",
    "    #display figure\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Call function to plot data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plotThicknessCompare(dataset, yearStart = 2018, regionsText = 'Inner Arctic')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sea ice type\n",
    "Now we want to know the percentage of each ice type (multi year vs. first year ice) in the region/s of interest, and add to our dataset. We will define a function that generates a plot to visualize the data. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Calculate percent ice type and add to dataset \n",
    "Function calculates monthly percent multi year ice and first year ice in the dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def calcPercentType(dataset): \n",
    "    \"\"\"Calculates percent ice type and adds to dataset.\n",
    "    \n",
    "    Args: \n",
    "        dataset (xr Dataset): dataset generated by Load_IS2 notebook\n",
    "    \n",
    "    Returns: \n",
    "        datasetFracIceType (xr Dataset): dataset with percent ice types added as data variables to the input dataset\n",
    "    \"\"\"  \n",
    "    #calculate percent multi year ice\n",
    "    MYI = dataset.where(dataset['ice_type_filled'] == 1, drop = True)\n",
    "    fracMYI = (MYI['ice_thickness_filled'].count(dim = ['x','y']) / dataset['ice_thickness_filled'].count(dim = ['x','y']))\n",
    "    percentMYI = fracMYI*100\n",
    "    percentMYI.attrs = {'description': 'percent multi year ice in dataset', 'units': '(0-100)%'}\n",
    "\n",
    "    #calculate percent first year ice\n",
    "    FYI = dataset.where(dataset['ice_type_filled'] == 0, drop = True)\n",
    "    fracFYI = (FYI['ice_thickness_filled'].count(dim = ['x','y']) / dataset['ice_thickness_filled'].count(dim = ['x','y']))\n",
    "    percentFYI = fracFYI*100\n",
    "    percentFYI.attrs = {'description': 'percent first year ice in dataset', 'units': '(0-100)%'}\n",
    "\n",
    "    #add percentages as coordinates to new dataset\n",
    "    datasetFracIceType = dataset.assign_coords(coords = {'percent_MYI': percentMYI, 'percent_FYI': percentFYI})\n",
    "    \n",
    "    return datasetFracIceType"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Call function to update dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset = calcPercentType(dataset)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plot ice thickness means and percent multi year ice \n",
    "Define a function to plot multi year, first year, and total mean monthly ice thickness, along with percent multi year ice on twin axes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plotThicknessAndFrac(dataset, title = None, ylim = None, ylimFrac = None, figPath = None):\n",
    "    \"\"\" Plots multi year, first year, and total mean monthly ice thickness, along with percent multi year ice on twin axes. \n",
    "    \n",
    "    Args: \n",
    "        dataset (xr Dataset): dataset generated by Load_IS2 notebook\n",
    "        title (str, optional): title string to add to plot \n",
    "        ylim (list, optional): list containing [min value, max value] for limits of y axis for plotting ice thickness (defaults to matplotlib generated limits)\n",
    "        ylimFrac (list, optional): list containing [min value, max value] for limits of y axis for plotting ice thickness (defaults to matplotlib generated limits)\n",
    "        figPath (str, optional): path to save fig (default to None)\n",
    "        \n",
    "    Returns: \n",
    "        Figure displayed in notebook \n",
    "    \n",
    "    Restrictions: \n",
    "        dataset input needs to contain the following coordinates: mean_ice_thickness, mean_MYI_thickness, mean_FYI_thickness, percent_MYI, percent_FYI\n",
    "    \"\"\"\n",
    "    \n",
    "    #initialize figure\n",
    "    fig = plt.figure()\n",
    "    if title != None: \n",
    "        inputTitle = plt.title(title, y = 1.3, x = 0.45, fontsize = 'x-large', horizontalalignment = 'center')\n",
    "    ax = plt.axes([0, 0, 1, 1]) \n",
    "    gridlines = plt.grid(b = True, linestyle = '--', alpha = 0.4) #add gridlines\n",
    "    if ylim == None: \n",
    "        ax.set_ylim([min(datasetWinter['mean_FYI_thickness'].values) - 0.2, max(datasetWinter['mean_MYI_thickness'].values) + 0.2])\n",
    "    else: \n",
    "        ax.set_ylim(ylim)\n",
    "    \n",
    "    #add title describing regions with data \n",
    "    if 'regions with data' in list(dataset.attrs.keys()): \n",
    "        regionsText = dataset.attrs['regions with data']\n",
    "        regionsTitle = ax.text(x = 0.5, y = 1.05, s = 'Region/s: ' + regionsText, size = 12, transform=ax.transAxes, fontsize = 'large', horizontalalignment = 'center')\n",
    "\n",
    "    #define twin axis\n",
    "    axTwin = ax.twinx()\n",
    "    if ylimFrac == None: \n",
    "        axTwin.set_ylim([min(dataset['percent_MYI'].values) - 8, max(dataset['percent_MYI'].values) + 8])\n",
    "    else: \n",
    "        axTwin.set_ylim(ylimFrac)\n",
    "    axTwin.tick_params(axis='y', labelcolor = 'darkblue')\n",
    "\n",
    "    #plot data\n",
    "    dataset['percent_MYI'].plot(x = 'time', ax = axTwin, linestyle = '--', color = 'darkblue', label = 'Fraction MYI (0-100)%')\n",
    "    dataset['mean_MYI_thickness'].plot(x = 'time', ax = ax, linestyle = '-', color = 'blue', marker = 'o', label = 'Mean MYI thickness')\n",
    "    dataset['mean_FYI_thickness'].plot(x = 'time', ax = ax, linestyle = '-', color = 'magenta', marker = 'v', label = 'Mean FYI thickness')\n",
    "    dataset['mean_ice_thickness'].plot(x = 'time', ax = ax, linestyle = '-', color = 'black', marker = 's', label = 'Mean total ice thickness')\n",
    "\n",
    "    #add legends & labels \n",
    "    ax.set_ylabel('Mean ice thickness (m)')\n",
    "    ax.set_xlabel('Month')\n",
    "    axTwin.set_ylabel('Fraction MYI (0-100)%', color = 'darkblue')\n",
    "    linesAx, labelsAx = ax.get_legend_handles_labels() #get labels for lines plotted on ax\n",
    "    linesAxTwin, labelsAxTwin = axTwin.get_legend_handles_labels() #get labels for lines plotted on axTwin\n",
    "    ax.legend(linesAx + linesAxTwin, labelsAx + labelsAxTwin, bbox_to_anchor=(1.5, 1), fontsize = 10)\n",
    "\n",
    "    #save figure\n",
    "    if figPath != None:\n",
    "        plt.savefig(figPath, dpi = 200)\n",
    "        \n",
    "    #display figure\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To aid in data visualization, if we are comparing data from two winters it is helpful to make sure the plots use the same limits for the y axes. Below, we will define the limits for both axes and use them as arguments for the function above. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "minThickness = np.nanmin(dataset['mean_FYI_thickness'].values) - 0.2 \n",
    "minThickness = minThickness if minThickness > 0 else 0\n",
    "maxThickness = np.nanmax([max(dataset['mean_MYI_thickness'].values), max(dataset['mean_ice_thickness'].values)]) + 0.2\n",
    "ylimThickness = [round(minThickness, 1), round(maxThickness, 1)]\n",
    "print('ylimits for ice thickness axis: ' + str(ylimThickness) + ' (meters)')\n",
    " \n",
    "minMYIFrac = min(dataset['percent_MYI'].values) - 8\n",
    "minMYIFrac = minMYIFrac if minMYIFrac > 0 else -4\n",
    "maxMYIFrac = max(dataset['percent_MYI'].values) + 8\n",
    "maxMYIFrac = maxMYIFrac if maxMYIFrac > 10 else 100\n",
    "ylimFrac = [round(minMYIFrac, 1), round(maxMYIFrac, 1)]\n",
    "print('ylimits for percent multi year ice axis: ' + str(ylimFrac) + ' (%)')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Plot data for winter 2018-2019"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plotThicknessAndFrac(dataset.sel(time = slice('Nov 2018','Apr 2019')), title = 'Winter 18-19', ylim = ylimThickness, ylimFrac = ylimFrac)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Plot data for winter 2019-2020"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plotThicknessAndFrac(dataset.sel(time = slice('Nov 2019','Apr 2020')), title = 'Winter 19-20', ylim = ylimThickness, ylimFrac = ylimFrac)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
